const { ipcRenderer } = require('electron');
let wins = [];
let settingWin = null;

window.exports = {
    // 这里的hello与plugin.json中的code一致
    DefaultConfig: {
        mode: "none", // 无UI模式
        args: {
            // 插件执行入口
            enter: async (action, callbackSetList) => {
                const currentConfig = getCurrentConfig(action.payload);
                if(wins.length === 0){
                    await calculatePosition()
                    launch(currentConfig)
                }else{
                    launch(currentConfig)
                }
            },
        },
    },
    Setting: {
        mode: "none", // 无UI模式
        args: {
            enter: async (action, callbackSetList) => {
                try{
                    settingWin?.close();
                }catch(e){
                    console.log(e);
                }
                settingWin = null;
                await createSettingWindow();
            },
        },
    },
    Dynamic: {
        mode: "none", // 无UI模式
        args: {
            enter: async (action) => {
                let param = action.payload.replace(/华彩\//, '');
                const currentConfig = getCurrentConfig(param);
                if(wins.length === 0){
                    await calculatePosition()
                    launch(currentConfig)

                }else{
                    launch(currentConfig)
                }
            },
        },
    }
};

const defaultConfig = [
    {
        id: 'defaultyanhua',
        name: '礼花',
        data: [
            {
                shape: '',
                particleCount: 150,
                spread: 45,
                angle: 60,
                scalar: 1.5,
                startVelocity: 40,
                origin: { x: 0, y: 0.5},
                gravity: 1,
                decay: 0.94,
                ticks: 150,
                colors: []
            },
            {
                shape: '',
                particleCount: 150,
                spread: 45,
                angle: 120,
                scalar: 1.5,
                startVelocity: 40,
                origin: { x: 1, y: 0.5},
                gravity: 1,
                decay: 0.94,
                ticks: 150,
                colors: []
            }
        ]
    },
    {
        id: 'defaultsahua',
        name: '撒花',
        data:  {
            shape: '',
            particleCount: 150,
            spread: 60,
            angle: 90,
            scalar: 2,
            startVelocity: 20,
            origin: { x: 0.5, y: 0.3},
            gravity: 1,
            decay: 0.94,
            ticks: 100,
            colors: []
        }
    },
    {
        id: 'defaultxinxing',
        name: '心形',
        data: {
            shape: 'heart',
            particleCount: 150,
            spread: 180,
            angle: 90,
            scalar: 3,
            startVelocity: 25,
            origin: { x: 0.5, y: 0.2},
            gravity: 1,
            decay: 0.94,
            ticks: 100,
            colors: ["FFC0CB", "FF69B4", "FF1493", "C71585"],
        }
    },
    {
        id: 'defaultemoji',
        name: 'emoji',
        data: {
            shape: 'emoji',
            particleCount: 150,
            spread: 360,
            ticks: 100,
            gravity: 0,
            decay: 0.94,
            startVelocity: 30,
            origin: { x: 0.5, y: 0.5},
            emoji: '🦄'
        }
    }
]



const getCurrentConfig = (name) => {
    let configs = utools.dbStorage.getItem('confetti_configs');
    if(!configs){
        utools.dbStorage.setItem('confetti_configs', defaultConfig)
        configs = defaultConfig
    }

    const currentConfig = configs.find(item => item.name === name);
    
    return currentConfig?.data || {};
}

const calculatePosition = async (param = {}) => {
    const display = utools.getAllDisplays();
    
    for (let i = 0; i < display.length; i++) {
        const bounds = display[i].workArea;
        const width = bounds.width;
        const height = bounds.height;
        const x = bounds.x;
        const y = bounds.y;
        await createWindow({ width, height, x, y, ...param })
    }
}



const createWindow = (param) => {
    let { width, height, x, y } = param;
    return new Promise((resolve, reject) => {
        let win = window.utools.createBrowserWindow('./index.html', {
            title: '幻屑纷飞',
            width,
            height,
            x,
            y,
            frame: false,
            transparent: true,
            alwaysOnTop: true,
            fullscreen: true,
            skipTaskbar: true,
            hiddenInMissionControl: true,
            backgroundColor: "rgba(255,255,255,0)",
            webPreferences: {
                preload: "./preload.js",
            }
        }, () => {
            // win.webContents.openDevTools();
            resolve(win);
            wins.push(win);
            win.setAlwaysOnTop(true, 'pop-up-menu');
        })
    })
}


const createSettingWindow = () => {
    return new Promise((resolve, reject) => {
        settingWin = window.utools.createBrowserWindow('./setting.html', {
            title: '设置',
            width: 800,
            height: 600,
            frame: true,
            transparent: false,
            // alwaysOnTop: true,
            skipTaskbar: false,
            backgroundColor: "#ffffff",
            webPreferences: {
                preload: "./preload.js",
            }
        }, () => {
            settingWin.webContents.openDevTools();
            resolve(settingWin);
            utools.outPlugin();
            utools.hideMainWindow();
            // settingWin.setAlwaysOnTop(true, 'pop-up-menu');
        })
    })
}


const launch = (param = {}) => {
    wins.forEach(win => {
        win.webContents.send('launch', param)
    })
    utools.outPlugin();
    utools.hideMainWindow();
}

ipcRenderer.on('end', () => {
    wins = [];
    // utools.outPlugin();
    utools.hideMainWindow();
})